package middleware

import (
	"context"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"shop/api/internal/types"
	"shop/pkg"
	"time"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Code:    401,
				Message: "用户认证失败",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		Claims, err := pkg.TokenParse(token)
		if err != nil {
			resp := types.Response{
				Code:    401,
				Message: "Token解析失败",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		exp := Claims["exp"].(float64)
		now := time.Now().Unix()

		if exp < float64(now) {
			resp := types.Response{
				Code:    401,
				Message: "token已经失效",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}

		ctx := context.WithValue(r.Context(), "user_id", Claims["user_id"].(string))
		r = r.WithContext(ctx)
		// 5. 关键：调用next，继续处理后续请求（否则请求会被拦截）
		next.ServeHTTP(w, r)
		
	}
}
